package zlx.springcloudAlibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import zlx.commons.entities.CommonResult;
import zlx.commons.entities.Payment;
import zlx.springcloudAlibaba.service.PaymentService;

import javax.annotation.Resource;

@RestController
public class CircleController {
    public static String SERVER_URL="http://nacos-payment-provider";

    @Resource
    RestTemplate restTemplate;

    @RequestMapping("/consumer.fallback/{id}")
//    @SentinelResource(value = "fallback")//没有配置
//   @SentinelResource(value = "fallback",fallback = "handlerFallback")       //配置fallback处理异常
//    @SentinelResource(value = "fallback",blockHandler = "blockHandler")      //配置blockHandler处理异常，只负责sentinel的配置
    @SentinelResource(value = "fallback",blockHandler = "blockHandler",fallback = "handlerFallback"
                                ,exceptionsToIgnore = {IllegalArgumentException.class})//同时配置了fallback和blockHandler处理异常

    public CommonResult<Payment> fallback(@PathVariable("id") Long id){
        CommonResult<Payment> result=restTemplate.getForObject(SERVER_URL+"/paymentSQL/"+id,CommonResult.class,id);
        if(id==4){
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
        }else if(result.getData()==null){
            throw new NullPointerException("NullPointerException,该id没有对应记录，空指针异常");
        }
        return result;
    }
    //fallback兜底方法
    public CommonResult<Payment> handlerFallback(@PathVariable("id") Long id,Throwable e){
        Payment payment=new Payment(id,null);
        return new CommonResult<>(444,"兜底异常，exception内容"+e.getMessage(),payment);
    }
    //blockHandler方法
    public CommonResult<Payment> blockHandler(@PathVariable("id") Long id, BlockException e){
        Payment payment=new Payment(id,null);
        return new CommonResult<>(445,"blockHandler-sentinel限流，无此流水号，blockEtion内容"+e.getMessage(),payment);
    }
    //=======openFeign
    @Resource
    private PaymentService paymentService;


    @GetMapping("/consumer/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
        return paymentService.paymentSQL(id);
    }
}
